package com.sptus.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sptus.aop.AppIntercept;
import com.sptus.common.constant.CommonConstant;
import com.sptus.common.core.redis.RedisCache;
import com.sptus.config.DataLoaderConfig;
import com.sptus.entity.*;
import com.sptus.framework.service.BaseCommonService;
import com.sptus.framework.mqtt.MyMqttClient;
import com.sptus.service.IAppEquipmentService;
import com.sptus.service.ISptUserEquipmentService;
import com.sptus.service.ISptUserParentService;
import com.sptus.system.domain.DevInfoMsg1;
import com.sptus.system.domain.Equipment;
import com.sptus.system.domain.vo.AppInfo;
import com.sptus.system.domain.DevDictionaries;
import com.sptus.system.service.IDevInfoMsg1Service;
import com.sptus.system.service.ISptDevLogService;
import com.sptus.system.domain.vo.AppDataVo;
import com.sptus.util.DevSqlUtil;
import com.sptus.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "app端设备设置")
@RequestMapping("/sys/app/set")
public class MqttSetController {
    @Autowired
    private RedisCache redisUtil;
    @Autowired
    IAppEquipmentService equipmentService;
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    IDevInfoMsg1Service msg1Service;

    @Autowired
    DataLoaderConfig dataLoaderConfig;

    @Autowired
    ISptUserEquipmentService sptUserEquipmentService;

    @Resource
    private BaseCommonService baseCommonService;

    @Autowired
    ISptUserParentService sptUserParentService;

    @Autowired
    ISptDevLogService devLogService;


    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    static Semaphore semaphore = new Semaphore(1);


    @ApiOperation(value = "设置", notes = "setMsg")
    @AppIntercept
    @PostMapping(value = "kkk")
    public Result<Object> uploadLocal(SptUser sptUser){
        Result<Object> ok = Result.ok();
        ok.setResult("appUrl");
        return ok;
    }

    @GetMapping("getDevParameter")
    @ApiOperation(value = "设置参数回显", notes = "setMsg")
    @AppIntercept
    public Result<Object> getDevParameter(AppInfo appInfo, SptUser sptUser, HttpServletRequest request) {

        String header = request.getHeader("version");
        Result<Object> result = new Result<>();
        Integer id = sptUser.getId();
        // todo 首页真实数据返回
        if (StringUtils.isEmpty(appInfo.getSn())) {
            return result.error500("please enter sn");
        }
        ArrayList<String> ids = new ArrayList<>();
        LambdaQueryWrapper<SptUserParent> sptUserParentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserParentLambdaQueryWrapper.eq(SptUserParent::getUserId,sptUser.getId());
        sptUserParentLambdaQueryWrapper.eq(SptUserParent::getState,"1");
        List<HashMap<String,String>> sptUserParents = sptUserParentService.selectListInfo(sptUserParentLambdaQueryWrapper);
        if(sptUserParents.size()>0){
            ids.add(sptUserParents.get(0).get("parent_id"));
        }
        ids.add(sptUser.getId()+"");

        LambdaQueryWrapper<SptUserEquipment> sptUserEquipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserEquipmentLambdaQueryWrapper.eq(SptUserEquipment::getEquipmentId,appInfo.getSn());
        sptUserEquipmentLambdaQueryWrapper.in(SptUserEquipment::getUserId,ids);
        SptUserEquipment sptUserEquipment = sptUserEquipmentService.getBaseMapper().selectOne(sptUserEquipmentLambdaQueryWrapper);

        if(StringUtils.isEmpty(sptUserEquipment)){
            return result.error500("Please enter correctly sn");
        }

        LambdaQueryWrapper<Equipment> equipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        equipmentLambdaQueryWrapper.eq(Equipment::getSn,appInfo.getSn());

        List<Equipment> equipments = equipmentService.getBaseMapper().selectList(equipmentLambdaQueryWrapper);

        try {
            if(ObjectUtil.isEmpty(redisUtil.getCacheObject(CommonConstant.MSG_LOCK_SN_SET + equipments.get(0).getSn()))){
                redisUtil.setCacheObject(CommonConstant.MSG_LOCK_SN_SET + equipments.get(0).getSn(), "1",2, TimeUnit.SECONDS);
                HashMap<String, String> stringStringHashMap = new HashMap<>();
                stringStringHashMap.put("FORCE_TRAN","2");
                String jsonString = JSONObject.toJSONString(stringStringHashMap);
                if(!ObjectUtil.isEmpty(equipments.get(0).getMac())){
                    MyMqttClient.publishMessage("/"+equipments.get(0).getMac()+"/Rtesttopic",jsonString,1);
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }

        ArrayList<AppDataVo> appDataVos=new ArrayList<>();
        Result<Object> ok = Result.ok();
        if (StringUtils.isEmpty(header)){
            appDataVos = dataLoaderConfig.loadData(appInfo.getSn(),"old");
        }else {
            appDataVos = dataLoaderConfig.loadData(appInfo.getSn(),"new",sptUser.getId()+"");
        }
        ok.setResult(appDataVos);
        //todo 获取参数数据
        return ok;
    }

    @PostMapping("postDevParameter")
    @ApiOperation(value = "设置", notes = "setMsg")
    @AppIntercept
    public Result<Object> setDevParameter(@RequestBody AppInfo appInfo, SptUser sptUser) {
        Result<Object> result = new Result<>();
        Integer id = sptUser.getId();
        // todo 首页真实数据返回
        if (StringUtils.isEmpty(appInfo.getSn())) {
            return result.error500("请输入sn");
        }

        ArrayList<String> ids = new ArrayList<>();
        LambdaQueryWrapper<SptUserParent> sptUserParentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserParentLambdaQueryWrapper.eq(SptUserParent::getUserId,sptUser.getId());
        sptUserParentLambdaQueryWrapper.eq(SptUserParent::getState,"1");
        List<HashMap<String,String>> sptUserParents = sptUserParentService.selectListInfo(sptUserParentLambdaQueryWrapper);
        if(sptUserParents.size()>0){
            ids.add(sptUserParents.get(0).get("parent_id"));
        }
        ids.add(sptUser.getId()+"");

        LambdaQueryWrapper<SptUserEquipment> sptUserEquipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sptUserEquipmentLambdaQueryWrapper.eq(SptUserEquipment::getEquipmentId,appInfo.getSn());
        sptUserEquipmentLambdaQueryWrapper.in(SptUserEquipment::getUserId,ids);
        SptUserEquipment sptUserEquipment = sptUserEquipmentService.getBaseMapper().selectOne(sptUserEquipmentLambdaQueryWrapper);

        if(StringUtils.isEmpty(sptUserEquipment)){
            return result.error500("Please enter correctly sn");
        }

        LambdaQueryWrapper<Equipment> equipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        equipmentLambdaQueryWrapper.eq(Equipment::getSn,appInfo.getSn());
        Equipment equipment = equipmentService.getBaseMapper().selectOne(equipmentLambdaQueryWrapper);
        if (StringUtils.isEmpty(equipment)) {
            return result.error500("Please enter correctly sn");
        }
        ArrayList<DevDictionaries> devs = appInfo.getDevs();
        //设置参数
        if (StringUtils.isEmpty(equipment.getMac())) {
            return result.error500("Device offline");
        }



        HashMap<String, Object> stringObjectHashMap = verifyValue(appInfo.getSn(), appInfo.getCode(), appInfo.getValue());
        boolean equals = stringObjectHashMap.get("verify").equals(true);
        if(equals){
            appInfo.setEmail(sptUser.getEmail());
            String version= DataLoaderConfig.getGlobalData().get("spt.rds.dsp");

            if(appInfo.getValue().equals("0")){
                version= DataLoaderConfig.getGlobalData().get("spt.rds.dsp");
            }else if(appInfo.getValue().equals("9")){
                version= DataLoaderConfig.getGlobalData().get("spt.rds.remote");
            }
            try {
                devLogService.saveDevSetApp(appInfo,version);
            }catch (Exception e){
                System.out.println("日志保存失败");
            }

            updateValue(appInfo.getSn(), appInfo.getCode(), appInfo.getValue());
            DevSqlUtil.setDevParameters(appInfo.getCode(), appInfo.getValue(), equipment.getMac(),appInfo.getSn(),baseCommonService,"appID->"+sptUser.getId(),sptUser.getEmail());

            result.setCode(200);
        }else {
            result.setCode(500);
            result.setResult(stringObjectHashMap);
            result.setMessage(stringObjectHashMap.get("msg")+"");
        }

        return result;
    }


    public void  updateValue(String sn,String code,String value){
        if(code.equals("RL")){
            LambdaQueryWrapper<DevInfoMsg1> qw=new LambdaQueryWrapper();
            qw.eq(DevInfoMsg1::getSn,sn);
            DevInfoMsg1 devInfoMsg1 = new DevInfoMsg1();
            if (value.indexOf(0) ==0){  devInfoMsg1.setRl(value.substring(1));}else {
                devInfoMsg1.setRl(value);
            }

            msg1Service.update(devInfoMsg1,qw);
        }
    }
    public  HashMap<String, Object> verifyValue(String sn,String code,String value){
        HashMap<String, Object> stringStringHashMap = new HashMap<>();
        ArrayList<DevDictionaries> devDictionaries = new ArrayList<>();
        ArrayList<HashMap<String, String>> hashMaps = new ArrayList<>();
        HashMap<String, String> codes = new HashMap<>();
        stringStringHashMap.put("verify",true);
        //13 14
        if(code.equals("SP")){
            DevDictionaries devDictionaries1 = new DevDictionaries();
            devDictionaries1.setName("13 Operation Mode");
            devDictionaries1.setCode("RL");
            devDictionaries1.setRelevanceTable("dev_info_msg1");
            devDictionaries1.setDataType(1);
            devDictionaries1.setDescription("Refer to Section 12 for the detailed operation");
            devDictionaries1.setClassify(2 + "");
            devDictionaries1.setState(1 + "");
            devDictionaries.add(devDictionaries1);
            List<DevDictionaries> devDictionariesList = DevSqlUtil.DevDataSql(devDictionaries, jdbcTemplate, sn);
            DevDictionaries devDictionariesRL = devDictionariesList.get(0);
            String valueRL = devDictionariesRL.getValue().split(" ")[0];
            if(!valueRL.equals("77")){
                stringStringHashMap.put("verify",false);
                stringStringHashMap.put("msg","please select 13 HBD");
                codes.put("RL","077");
                hashMaps.add(codes);
                stringStringHashMap.put("codes",hashMaps);
            }
        }
        //01,02,40关联
        if(code.equals("SP")){
            DevDictionaries devDictionaries1 = new DevDictionaries();
            devDictionaries1.setName("13 Operation Mode");
            devDictionaries1.setCode("RL");
            devDictionaries1.setRelevanceTable("dev_info_msg1");
            devDictionaries1.setDataType(1);
            devDictionaries1.setDescription("Refer to Section 12 for the detailed operation");
            devDictionaries1.setClassify(2 + "");
            devDictionaries1.setState(1 + "");
            devDictionaries.add(devDictionaries1);
            List<DevDictionaries> devDictionariesList = DevSqlUtil.DevDataSql(devDictionaries, jdbcTemplate, sn);
            DevDictionaries devDictionariesRL = devDictionariesList.get(0);
            String valueRL = devDictionariesRL.getValue().split(" ")[0];
            if(!valueRL.equals("77")){
                stringStringHashMap.put("verify",false);
                stringStringHashMap.put("msg","please select 13 HBD");
                codes.put("RL","077");
                hashMaps.add(codes);
                stringStringHashMap.put("codes",hashMaps);
            }
        }
        //17,18关联16
//        if(code.equals("SP")){
//            DevDictionaries devDictionaries1 = new DevDictionaries();
//            devDictionaries1.setName("13 Operation Mode");
//            devDictionaries1.setCode("RL");
//            devDictionaries1.setRelevanceTable("dev_info_msg1");
//            devDictionaries1.setDataType(1);
//            devDictionaries1.setDescription("Refer to Section 12 for the detailed operation");
//            devDictionaries1.setClassify(2 + "");
//            devDictionaries1.setState(1 + "");
//            devDictionaries.add(devDictionaries1);
//            List<DevDictionaries> devDictionariesList = DevSqlUtil.DevDataSql(devDictionaries, jdbcTemplate, sn);
//            DevDictionaries devDictionariesRL = devDictionariesList.get(0);
//            String valueRL = devDictionariesRL.getValue().split(" ")[0];
//            if(!valueRL.equals("77")){
//                stringStringHashMap.put("verify",false);
//                stringStringHashMap.put("msg","please select 13 HBD");
//                codes.put("RL","077");
//                hashMaps.add(codes);
//                stringStringHashMap.put("codes",hashMaps);
//            }
//        }
//       // 21-24 关联15
//        if(code.equals("SP")){
//            DevDictionaries devDictionaries1 = new DevDictionaries();
//            devDictionaries1.setName("13 Operation Mode");
//            devDictionaries1.setCode("RL");
//            devDictionaries1.setRelevanceTable("dev_info_msg1");
//            devDictionaries1.setDataType(1);
//            devDictionaries1.setDescription("Refer to Section 12 for the detailed operation");
//            devDictionaries1.setClassify(2 + "");
//            devDictionaries1.setState(1 + "");
//            devDictionaries.add(devDictionaries1);
//            List<DevDictionaries> devDictionariesList = DevSqlUtil.DevDataSql(devDictionaries, jdbcTemplate, sn);
//            DevDictionaries devDictionariesRL = devDictionariesList.get(0);
//            String valueRL = devDictionariesRL.getValue().split(" ")[0];
//            if(!valueRL.equals("77")){
//                stringStringHashMap.put("verify",false);
//                stringStringHashMap.put("msg","please select 13 HBD");
//                codes.put("RL","077");
//                hashMaps.add(codes);
//                stringStringHashMap.put("codes",hashMaps);
//            }
//        }


        return stringStringHashMap;
    }



//    int str=0;
//    @PostMapping("/index.html")
//    @ApiOperation(value="设置", notes="setMsg")
//    public  String  postIndex(@RequestParam String stassid, @RequestParam String stapwd)   {
//
//
//
//        cachedThreadPool.submit(new Runnable() {
//            @Override
//            public void run() {
//
//                try {
//                    semaphore.acquire();
//                    System.out.println(str+=1);
//                    Thread.sleep(2000);
//
//                }catch (InterruptedException e){
//
//                }finally {
//                    semaphore.release();
//                }
//            }
//        });
//
////        redisUtil.set("msgKey"+stassid,stapwd,2);
//        return "stassid:"+stassid+"  stapwd"+stapwd;
//    }

}
